﻿using HZH_Controls;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodePrinter.Util
{
	public class CodeUtil
	{
		///单例
		public static CodeUtil instance = new CodeUtil();
		string path = "UsedCode.co";
		 List<string> Code = new List<string>();
		private void LockMethod(Action act) {
			lock (this)
			{
				act.Invoke();
			}
		}
		public void Clear()
		{
			LockMethod(() =>
			{
				Code.Clear();
			});

			}
		public bool AddCode(string code) {
			if (Code.Contains(code))
			{
				return false;
			}
			LockMethod(() => { 
			Code.Add(code);
			});
			return true;
		}
		public void InitCode() {

			FileStream str= null; 
			try
			{
				if (!File.Exists(path)) 
				{
					str = File.Create(path);
				}
				else
				{
					str = File.OpenRead(path);
				}
				byte[] bt = new byte[str.Length];
				str.Read(bt, 0, bt.Length);
				string code=  Encoding.ASCII.GetString(bt);
				if (!string.IsNullOrWhiteSpace(code))
				{
					Code.AddRange(code.Split(','));
				}
			}
			catch (Exception ex)
			{
				throw ex;
			}
			finally { 
				str?.Close();
			}
		}


		public void SaveCode() 
		{
			FileStream str = null;
			try
			{
				if (File.Exists(path)) { 
					File.Delete(path); 
				}
				
					str = File.Create(path);
				
				
				var strs = string.Join(",",Code);
				byte[] bt = strs.ToBytes();
				str.Write(bt, 0, bt.Length);
				
			}
			catch (Exception ex)
			{
				throw ex;

			}
			finally
			{
				str?.Flush();
				str?.Close();
			}
		}
	}
}
